//
//  SRRegisterViewController.m
//  SportRing
//
//  Created by Apple on 14/10/23.
//  Copyright (c) 2014年 HotOne. All rights reserved.
//

#import "SRRegisterViewController.h"
#import "SRRegisterView.h"
#import "SRAccountNetService.h"
#import "SRManager.h"
#import "SRDB.h"
#import "Utils.h"
#import <CoreBluetooth/CoreBluetooth.h>

@interface SRRegisterViewController () <SRRegisterViewDelegate>

@property (nonatomic, weak) IBOutlet SRRegisterView * registerView;
@property (nonatomic, strong) NSString * selectPerName;

@end

@implementation SRRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addBackButton];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(didFindPeripheral)
//                                                 name:@"didFindPeripheral"
//                                               object:nil];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(0, 0, 130, 40);
    button.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMaxY(self.view.bounds) - 20);
    [button setTitle:@"已注册，点此登录" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(doGotoLoginView) forControlEvents:UIControlEventTouchUpInside];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button.titleLabel setFont:[UIFont boldSystemFontOfSize:14]];
    [_registerView addSubview:button];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.edgesForExtendedLayout=UIRectEdgeNone;
    self.navigationController.navigationBarHidden = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardwillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)notification
{
    //得到键盘高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    
    [UIView animateWithDuration:0.3 animations:^{
        _registerView.center = CGPointMake(_registerView.center.x, self.view.center.y - keyboardRect.size.height);
    }];
    
}

- (void)keyboardwillChange:(NSNotification *)notification
{
    //得到键盘高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    
    [UIView animateWithDuration:0.3 animations:^{
        _registerView.center = CGPointMake(_registerView.center.x, self.view.center.y - keyboardRect.size.height);
    }];
    
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    _registerView.center = self.view.center;

}

- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
    [self.view endEditing:YES];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
//    SRRegisterViewModel * viewModel = [self getViewModel];
//    self.registerView.viewModel = viewModel;
}

//- (SRRegisterViewModel *)getViewModel
//{
//    __block SRRegisterViewModel * viewModel = [[SRRegisterViewModel alloc] init];
//    
//#if TARGET_IPHONE_SIMULATOR
//    NSArray * devices = @[@"icmo-12345",@"icmo-12346", @"icmo-12347"];
//    [devices enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//        SRRingTableViewCellModel * cellModel = [[SRRingTableViewCellModel alloc] init];
//        cellModel.ringIdSting = obj;
//        [viewModel.cellModels addObject:cellModel];
//    }];
//#elif TARGET_OS_IPHONE
//    NSArray * devices = [SRManager sharedInstance].findDevices;
//    [devices enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//        CBPeripheral * per = obj;
//        SRRingTableViewCellModel * cellModel = [[SRRingTableViewCellModel alloc] init];
//        cellModel.ringIdSting = per.name;
//        [viewModel.cellModels addObject:cellModel];
//    }];
//#endif
//    return viewModel;
//}

#pragma mark - SRRegisterViewDelegate

- (void)doRegisterActionWithNickName:(NSString *)nickName
                              mobile:(NSString *)mobile
                            password:(NSString *)password
{
//    [self performSegueWithIdentifier:@"gotoInfoVC" sender:self];
//    return;
    [SVProgressHUD show];
    if (mobile.length != 11) {
       [SVProgressHUD showErrorWithStatus:@"手机号码错误"];
        return;
    }
    if (!(password.length >= 6 && password.length <= 20)) {
        [SVProgressHUD showErrorWithStatus:@"请设置6～20位密码"];
        return;
    }
    @weakify(self);
    [[SRAccountNetService registerWithUserName:mobile
                                      userPwd:password
                                     nickName:nickName]
     subscribeNext:^(id x) {
         if ([x isKindOfClass:[NSError class]])
         {
             [SVProgressHUD showErrorWithStatus:@"注册失败"];
         }
         else
         {
             [SVProgressHUD showSuccessWithStatus:@"注册成功"];
             
             //登陆成功保存userToken
             SRMe *me = x;
             [Utils saveUserLoginToken:me];
             
             if (self_weak_.selectPerName.length > 0) {
                 SRDevice * device = [SRDevice findDeviceCINEForMe:[SRMe currentUser]];
                 [device configAttributesWithBlock:^(SRDevice *deviceSelf) {
                     deviceSelf.name = self_weak_.selectPerName;
                 }];
                 [[SRManager sharedInstance] setCurrentPeripheralName:self_weak_.selectPerName];
             }
             [self_weak_ performSegueWithIdentifier:@"gotoInfoVC" sender:self];
         }
     } error:^(NSError *error) {
         if (error.code == 2005) {
             [SVProgressHUD showErrorWithStatus:@"用户名已经被注册"];
         }else
         {
             [SVProgressHUD showErrorWithStatus:@"注册失败"];
         }
     }];
}

//-(void)didFindPeripheral
//{
//    SRRegisterViewModel * viewModel = [self getViewModel];
//    self.registerView.viewModel = viewModel;
//}

- (void)doGotoLoginView
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)selectedRing:(NSString *)perName
{
    self.selectPerName = perName;
}

@end
